<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <jsp:include page="../inc/js.jsp"/>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>用户管理</title>
    <jsp:include page="../inc/css.jsp"/>

    <style>
        /* 添加CSS样式 */
        .custom-switch-container {
            display: inline-block;
            position: relative;
            font-size: 14px;
            line-height: 1.5;
            margin: 0 8px;
        }

        .custom-switch-input {
            position: absolute;
            opacity: 0;
            width: 0;
            height: 0;
        }

        .custom-switch-track {
            position: relative;
            display: inline-block;
            width: 44px;
            height: 24px;
            background-color: #f5f5f5;
            border: 1px solid #d9d9d9;
            border-radius: 100px;
            cursor: pointer;
            transition: all 0.3s;
            vertical-align: middle;
        }

        .custom-switch-track::after {
            content: '';
            position: absolute;
            top: 2px;
            left: 2px;
            width: 18px;
            height: 18px;
            background-color: #fff;
            border-radius: 50%;
            box-shadow: 0 2px 4px 0 rgba(0, 35, 11, 0.2);
            transition: all 0.3s;
        }

        .custom-switch-input:checked + .custom-switch-track {
            background-color: #1890ff;
            border-color: #1890ff;
        }

        .custom-switch-input:checked + .custom-switch-track::after {
            left: calc(100% - 20px);
        }
    </style>
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
    <jsp:include page="../inc/menu.jsp"/>

    <div class="content-wrapper">
        <section class="content">
            <div class="row">
                <div class="col-12">
                    <div class="card" style="margin-top: 10px">
                        <div class="card-header">
                            <h4>${user.nickName} - （${user.name}）</h4>

                            <c:if test="${sessionScope.session_master_id == 1}">
                                <button type="button" title="添加关联设备" class="btn btn-primary" style="margin-right: 6px;" onclick="_childList.fn.addInfo()">添加关联设备</button>
                            </c:if>

                            <button type="button" title="查询" style="margin-right: 6px;" class="btn btn-info" onclick="_childList.fn.reloadData()">查询</button>
                            <button type="button" title="返回用户列表" class="btn btn-warning" onclick="_childList.fn.goBack()">返回</button>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-striped table-bordered table-hover" id="dataTables" style="width: 99%">
                                    <colgroup>
                                        <col class="gradeA even"/>
                                        <col class="gradeA odd"/>
                                        <col class="gradeA even"/>
                                        <col class="gradeA odd"/>
                                        <col class="gradeA even"/>
                                        <col class="gradeA odd"/>
                                        <col class="gradeA even"/>
                                        <col class="gradeA odd"/>
                                        <c:if test="${sessionScope.session_master_id == 1}">
                                            <col class="gradeA even"/>
                                        </c:if>
                                    </colgroup>
                                    <thead>
                                    <tr>
                                        <th>所属公司</th>
                                        <th>设备名称</th>
                                        <th>设备识别码</th>
                                        <th>实时预警</th>
                                        <th>分钟预警</th>
                                        <th>小时预警</th>
                                        <th>日均预警</th>
                                        <th>查看数据</th>
                                        <c:if test="${sessionScope.session_master_id == 1}">
                                            <th>操作</th>
                                        </c:if>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    <!-- /.card -->
                </div>
                <!-- /.col -->
            </div>
            <!-- /.row -->
        </section>
        <!-- /.content -->
    </div>
</div>
<!-- ./wrapper -->

<div class="modal inModal fade" id="deviceAddModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">添加关联设备</h4>
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            </div>
            <div class="modal-body">
                <form role="form" class="form-group">
                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-2">选择设备：</label>

                        <div class="col-10">
                            <select id="deviceList" class="form-control">
                                <option value="">全部设备</option>
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="_childList.fn.saveDeviceUserInfo()">确定</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<input id="hiddenUserId" type="hidden" value="${user.id}"/>
<input id="hiddenUserCompanyId" type="hidden" value="${user.companyList}"/>

<!-- page script -->
<script type="text/javascript">
    let _childList = {
        v: {
            list: [],
            dTable: null
        },
        fn: {
            init: function () {
                _childList.fn.getDeviceList();

                _childList.fn.dataTableInit();
            },
            goBack: function () {
                window.history.go(-1);
            },
            getDeviceList: function () {
                $.post('common/deviceList', {
                    companyId: $('#masterCompanyId').val()
                }, function (result) {
                    if (result.length > 0) {
                        let content = '';
                        $.each(result, function (i, item) {
                            content += '<option value="' + item.code + '">' + item.name + '（' + item.code + '）</option>';
                        });

                        $('#deviceList').append(content);
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            addInfo: function () {
                $('#deviceList').val('');

                $("#deviceAddModal").modal("show");
            },
            reloadData: function () {
                _childList.v.list = [];
                _childList.v.dTable.DataTable().ajax.reload(null, false);
            },
            dataTableInit: function () {
                _childList.v.dTable = $tutu.dataTable($('#dataTables'), {
                    "processing": true,
                    "serverSide": true,
                    "autoWidth": true,//自动计算宽度
                    "lengthChange": false,//是否允许用户改变表格每页显示的记录数
                    "searching": false,
                    "ordering": false,
                    "ajax": {
                        "url": "backend/user/child/list",
                        "type": "POST",
                        "data": {
                            "userId": $('#hiddenUserId').val()
                        }
                    },
                    "language": $tutu.v.dataTableL,
                    "columns": [
                        {"data": "device.company.name"},
                        {"data": "device.name"},
                        {"data": "device.code"},
                        {
                            "data": null,
                            render: function (data) {
                                let str = '<label class="custom-switch-container">';

                                if (data.timeFlag === 1) {
                                    str += '<input type="checkbox" class="custom-switch-input" id="switch-' + data.device.code + '-2011-' + data.timeFlag + '" onchange="_childList.fn.changeTimeStatus(this)" checked>';
                                } else {
                                    str += '<input type="checkbox" class="custom-switch-input" id="switch-' + data.device.code + '-2011-' + data.timeFlag + '" onchange="_childList.fn.changeTimeStatus(this)">';
                                }

                                str += '<span class="custom-switch-track"></span></label>';
                                return str;
                            }
                        },
                        {
                            "data": null,
                            render: function (data) {
                                let str = '<label class="custom-switch-container">';

                                if (data.minuteFlag === 1) {
                                    str += '<input type="checkbox" class="custom-switch-input" id="switch-' + data.device.code + '-2051-' + data.minuteFlag + '" onchange="_childList.fn.changeTimeStatus(this)" checked>';
                                } else {
                                    str += '<input type="checkbox" class="custom-switch-input" id="switch-' + data.device.code + '-2051-' + data.minuteFlag + '" onchange="_childList.fn.changeTimeStatus(this)">';
                                }

                                str += '<span class="custom-switch-track"></span></label>';
                                return str;
                            }
                        },
                        {
                            "data": null,
                            render: function (data) {
                                let str = '<label class="custom-switch-container">';

                                if (data.hourFlag === 1) {
                                    str += '<input type="checkbox" class="custom-switch-input" id="switch-' + data.device.code + '-2061-' + data.hourFlag + '" onchange="_childList.fn.changeTimeStatus(this)" checked>';
                                } else {
                                    str += '<input type="checkbox" class="custom-switch-input" id="switch-' + data.device.code + '-2061-' + data.hourFlag + '" onchange="_childList.fn.changeTimeStatus(this)">';
                                }

                                str += '<span class="custom-switch-track"></span></label>';
                                return str;
                            }
                        },
                        {
                            "data": null,
                            render: function (data) {
                                let str = '<label class="custom-switch-container">';

                                if (data.dayFlag === 1) {
                                    str += '<input type="checkbox" class="custom-switch-input" id="switch-' + data.device.code + '-2031-' + data.dayFlag + '" onchange="_childList.fn.changeTimeStatus(this)" checked>';
                                } else {
                                    str += '<input type="checkbox" class="custom-switch-input" id="switch-' + data.device.code + '-2031-' + data.dayFlag + '" onchange="_childList.fn.changeTimeStatus(this)">';
                                }

                                str += '<span class="custom-switch-track"></span></label>';
                                return str;
                            }
                        },
                        {
                            "data": null,
                            render: function (data) {
                                let str = '<label class="custom-switch-container">';

                                if (data.dataFlag === 1) {
                                    str += '<input type="checkbox" class="custom-switch-input" id="switch-' + data.device.code + '-1010-' + data.dataFlag + '" onchange="_childList.fn.changeTimeStatus(this)" checked>';
                                } else {
                                    str += '<input type="checkbox" class="custom-switch-input" id="switch-' + data.device.code + '-1010-' + data.dataFlag + '" onchange="_childList.fn.changeTimeStatus(this)">';
                                }

                                str += '<span class="custom-switch-track"></span></label>';
                                return str;
                            }
                        }
                        <c:if test="${sessionScope.session_master_id == 1}">
                        , {"data": null}
                        </c:if>
                    ],
                    /*添加小插件*/
                    "columnDefs": [
                        {
                            "data": null,
                            "defaultContent": "<button type='button' title='告警规则列表' class='btn btn-primary btn-sm alarmTable'>" +
                                "<i class='fa fa-table'></i>" +
                                "</button>" +
                                "&nbsp;&nbsp;" +
                                "<button type='button' title='删除' class='btn btn-danger btn-sm delete'>" +
                                "<i class='fa fa-remove'></i>" +
                                "</button>",
                            "targets": -1
                        }
                    ],
                    "createdRow": function (row, data, index) {
                        _childList.v.list.push(data);
                    },
                    rowCallback: function (row, data) {
                        $('td', row).last().find(".alarmTable").click(function () {
                            window.location.href = 'backend/user/alarmRule/index?deviceCode=' + data.device.code + '&userId=' + $('#hiddenUserId').val() + '&pageNum=' + $tutu.currentPage;
                        });

                        $('td', row).last().find(".delete").click(function () {
                            //if (!$('#hiddenUserCompanyId').val().includes('@' + data.device.company.id + '@')) {
                                _childList.fn.delInfo(data.device.code);
                            //} else {
                            //    info("用户所属公司的设备不允许删除", "warning");
                            //}
                        });
                    },
                    "fnServerParams": function (aoData) {
                        _childList.v.list = [];
                    },
                    "fnDrawCallback": function (data) {
                        $tutu.uiForm(data);

                        // 初始化
                        $('input.form_switch').each(function (idx, el) {
                            $(this).Switch().addClass('class_name');
                        });
                    }
                });
            },
            changeTimeStatus: function (self) {
                const isChecked = $(self).prop('checked');
                const switchId = $(self).attr('id');
                const str = switchId.split("-");

                startLoading();

                $.post('backend/user/updateDeviceUser', {
                    deviceCode: str[1],
                    userId: $('#hiddenUserId').val(),
                    type: str[2],
                    flag: isChecked ? 1 : 0
                }, function (result) {
                    endLoading();

                    if (result.code === 0) {
                        info("设备用户数据访问状态修改成功", "success");

                        _childList.fn.reloadData();
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            saveDeviceUserInfo: function () {
                startLoading();

                $.post('backend/user/updateDeviceUser', {
                    deviceCode: $('#deviceList').val(),
                    userId: $('#hiddenUserId').val(),
                    type: 1010,
                    flag: 1
                }, function (result) {
                    endLoading();

                    if (result.code === 0) {
                        info("设备关联信息添加成功", "success");

                        $("#deviceAddModal").modal("hide");

                        _childList.fn.reloadData();
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            delInfo: function (deviceCode) {
                swal({
                    title: "您确定要删除这条记录吗",
                    text: "删除后将无法恢复，请谨慎操作！",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "是的，删除！",
                    cancelButtonText: "不，取消",
                    closeOnConfirm: false,
                    closeOnCancel: false
                }, function (isConfirm) {
                    if (isConfirm) {
                        startLoading();

                        $.post('backend/user/updateDeviceUser', {
                            deviceCode: deviceCode,
                            userId: $('#hiddenUserId').val(),
                            type: 5,
                            flag: 0
                        }, function (result) {
                            endLoading();

                            if (result.code === 0) {
                                swal("删除成功！", "您已经删除了这条记录。", "success");

                                _childList.fn.reloadData();
                            } else {
                                info(result.msg, "error");
                            }
                        });
                    } else {
                        swal("已取消", "您取消了删除操作！", "error");
                    }
                })
            }
        }
    };

    $(document).ready(function () {
        _childList.fn.init();

        window.onload = function () {
            checkSelectMenu("userLi");

            loadMenuColor('userLi');
        }
    });
</script>
</body>
</html>